<script setup>
import commonTable from '@/components/commonTable.vue';
import xmlDialog from '@/components/xml/index.vue';
import addDialog from './components/addDialog.vue';
import useStore from '@/stores';

import {
  getFlowDataListAysnc,
  getFlowChartXMLAsync,
  updateFlowStateAsync,
  deleteFlowAsync,
} from '@/api/flowManagement'
const { useAPIStore } = useStore()
//关键词搜索
const formData = ref({
  key: ''
})

const tableData = ref([])
const tableHeader = ref([

  {
    data: {
      prop: 'flowKey',
      label: '流程KEY',
    },
  }, {
    data: {
      prop: 'name',
      label: '流程名称',
    },
  },
  {
    data: {
      prop: 'id',
      label: '流程定义id',
    },
  },
  {
    data: {
      prop: 'formKey',
      label: '绑定表单key',
    }
  },
  {
    data: {
      prop: 'deployDate',
      label: '部署日期',
    },
  },
  {
    data: {
      prop: 'version',
      label: '版本',
      width: '60'
    }

  },
  {
    slot: 'state',
    data: {
      label: '状态',
      width: '60'
    }
  },
  {
    slot: 'preview',
    data: {
      label: '预览表单',
      width: '100'
    }
  },
  {
    slot: 'operate',
    data: {
      label: '操作'
    }
  }
])
const pagination = ref({
  size: 10,
  total: 10,
  curPage: 1,
  pageSizes: [3, 5, 10, 20]

})
// 表格加载动画
const isLoading = ref(false)

//获取表格数据
const getTabelData = async () => {
  try {
    isLoading.value = true
    const params = {
      key: formData.value.key,
      currPage: pagination.value.curPage,
      pageSize: pagination.value.size
    }
    // 调接口
    const { data: res } = await getFlowDataListAysnc(params)

    console.log('%c [  ]-85', 'font-size:13px; background:pink; color:#bf2c9f;', res)

    console.log('%c [  ]-87', 'font-size:13px; background:pink; color:#bf2c9f;', res.rows && Array.isArray(res.rows) && res.rows.length)
    if (res.rows && Array.isArray(res.rows) && res.rows.length) {
      tableData.value = res.rows
    } else {
      tableData.value = []
    }
    pagination.value.total = +res.total

    isLoading.value = false


  } catch (error) {
    isLoading.value = false
    ElMessage.error(error)
    console.log('%c [ error ]-109', 'font-size:13px; background:pink; color:#bf2c9f;', error)
  }
}

//关键字查询| 刷新数据
const searchHandle = () => {
  pagination.value.curPage = 1
  getTabelData()
}

//部署
const addHandle = () => {
  addDialogVisible.value = true
}

//页大小改变
const handleSizeChange = (val) => {
  pagination.value.size = val
  getTabelData()
}
//切换页
const handleCurrentChange = (val) => {
  pagination.value.curPage = val
  getTabelData()
}

//查看流程图
const getFlowChart = async (info) => {
  try {
    const params = {
      ...info
    }
    const xmlRes = await getFlowChartXMLAsync(params)
    if (xmlRes) {
      console.log('%c [  ]-138', 'font-size:13px; background:pink; color:#bf2c9f;', '成功获取流程图相关内容')
      const src = `${useAPIStore.img_base_url}lanlu/flowDefinition/flowImg?procDefId=${info.id}`
      xml.value = {
        src: src,
        str: xmlRes
      }
      flowChartDialogVisible.value = true
    }
  } catch (error) {
    console.log('%c [ error ]-134', 'font-size:13px; background:pink; color:#bf2c9f;', error)
  }
}


//改变流程状态
const updateFlowState = async (info) => {
  try {

    const res = await updateFlowStateAsync(info)
    if (res && res.code + '' === '200') {
      getTabelData()
      ElMessage.success(`成功修改【${info.name}】的状态`)
    }
  } catch (error) {
    console.log('%c [ error ]-139', 'font-size:13px; background:pink; color:#bf2c9f;', error)
    ElMessage.error('改变状态失败，请重新尝试！')

  }

}

//删除流程
const deletedFlow = async (info) => {
  try {
    const res = await deleteFlowAsync(info)
    if (res && res.code + '' === '200') {
      ElMessage.success(`成功删除流程图【${info.name}】`)
      //刷新数据
      searchHandle()

    }
  } catch (error) {
    console.log('%c [ error ]-155', 'font-size:13px; background:pink; color:#bf2c9f;', error)
    ElMessage.error('删除失败，请重新尝试！')
  }
}

//流程图文件
const xml = ref({})

//用户弹窗标识
const flowChartDialogVisible = ref(false)

const closeDialog = () => {
  flowChartDialogVisible.value = false
}

const addDialogVisible = ref(false)
const closeAddDialog = (flag) => {
  console.log('%c [  ]-23', 'font-size:13px; background:pink; color:#bf2c9f;', '??')

  addDialogVisible.value = false
  if (flag) {
    getTabelData()
  }
}

//预览表单弹窗的数据
const previewData = ref({})
const previewVisible = ref(false)
//预览表单
const previewFormHandle = async (info) => {
  if (!info.formMsg || !JSON.parse(info.formMsg).length) return ElMessage.error(`流程【${info.name}】没有绑定对应的表单，请先进行绑定！`)
  previewData.value = {
    optionList: JSON.parse(info.formMsg)?.map(item => {
      item.data = {
        label: item.label,
        prop: item.fieldName
      }
      return {
        data: {
          label: item.label,
          prop: item.fieldName
        },
        $attrs: item.$attrs,
        component: item.componentName,
        required: item.required
      }
    }),
    title: info.name,
  }

  previewVisible.value = true
}

onMounted(() => {
  getTabelData()
})

</script>


<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class='card-header'>
          <el-form>
            <el-form-item label="流程名称关键词" prop="key">
              <el-input class="search-inp" v-model="formData.key" placeholder="请输入关键字" clearable></el-input>
            </el-form-item>
          </el-form>

          <el-button class="btn-blue" type="primary" plain :icon="Search" @click="searchHandle">
            <el-icon>
              <Search />
            </el-icon>
            <span>查询</span>
          </el-button>
          <el-button class="btn-green" type="success" plain :icon="Plus" @click="addHandle">
            <el-icon>
              <Plus />
            </el-icon>
            <span>部署</span>
          </el-button>
        </div>
      </template>

      <commonTable :tableData="tableData" :tableHeader="tableHeader" :isLoading="isLoading">
        <template #state='{ scope }'>
          <el-tag v-if="scope.suspensionState + '' === '1'" type="success">正常</el-tag>
          <el-tag v-if="scope.suspensionState + '' === '2'" type="danger">挂起</el-tag>
        </template>

        <template #preview="{ scope }">
          <el-tag type="warning" class="preview-btn" @click='previewFormHandle(scope)'>预览表单</el-tag>
        </template>

        <template #operate="{ scope }">
          <el-tooltip content="查看流程图" placement="bottom">
            <el-button type="primary" plain circle @click="getFlowChart(scope)">
              <el-icon>
                <DataBoard />
              </el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip content="改变状态" placement="bottom">
            <el-button type="warning" plain circle @click="updateFlowState(scope)">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
          </el-tooltip>

          <el-popconfirm title="你确定要删除该流程嘛?" @confirm="deletedFlow(scope)">
            <template #reference>
              <el-button type="danger" plain circle>
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-popconfirm>

        </template>
      </commonTable>

      <template #footer>
        <div class="card-footer">
          <el-pagination background layout="total,prev, pager, next, sizes" :total="pagination.total"
            :page-sizes="pagination.pageSizes" :current-page="pagination.curPage" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </template>
    </el-card>
  </div>

  <!-- 查看流程图 -->
  <xmlDialog :visible="flowChartDialogVisible" :xml="xml" @closeDialog="closeDialog">
  </xmlDialog>
  <!-- 部署 -->
  <addDialog :visible="addDialogVisible" @closeAddDialog="closeAddDialog">
  </addDialog>

  <!-- 阅览表单 -->
  <previewForm :visible="previewVisible" :optionList="previewData.optionList" :title="previewData.title"
    @closeDialog="previewVisible = false" />

</template>

<style lang="scss" scoped>
.user-container {

  .card-header {
    display: flex;

    .search-inp {
      width: 200px;
      margin-right: 10px;
    }

    :deep(.el-button) {
      color: #fff;
      width: 100px;
      height: 35px;
      font-size: 16px;
      border-color: #c6c6c6;
    }
  }

  .card-footer {
    display: flex;
    justify-content: flex-end;

  }

  .preview-btn {
    cursor: pointer;
  }
}


:deep(.el-form-item__label) {
  font-weight: 700;
}
</style>